<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div v-for="(item,index) in roleList" :key="item.roleId" class="role-item" :class="{active:index === activeIndex}" @click="changeAtive(index)">
        <div class="role-info">
          <svg-icon :icon-class="index===activeIndex ? 'user-active' : 'user'" class="icon" />
          {{ item.roleName }}
        </div>
        <div class="more">
          <el-dropdown>
            <span class="el-dropdown-link">
              <svg-icon icon-class="more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="$router.push(`/roleAdd?id=${item.roleId}`)">编辑角色</el-dropdown-item>
              <el-dropdown-item @click="delRole(item.roleId)">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-button class="addBtn" size="mini" @click="$router.push('/roleAdd')">添加角色</el-button>
    </div>
    <div class="right-wrapper">
      <el-tabs v-model="activeName">
        <el-tab-pane label="功能权限" name="tree">
          <div class="tree-wrapper">
            <div v-for="item in treeList" :key="item.id" class="tree-item">
              <!-- title -->
              <div class="tree-title">{{ item.title }}</div>
              <!-- 树形结构 -->
              <el-tree
                ref="tree"
                :props="{label:'title'}"
                :data="item.children"
                show-checkbox
                :default-expand-all="true"
                node-key="id"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员${userList.length}`" name="user">
          <div class="user-wrapper">
            <el-table
              :data="userList"
              style="width: 100%"
            >
              <el-table-column
                type="index"
                width="250"
                label="序号"
              />
              <el-table-column
                prop="name"
                label="员工姓名"
              />
              <el-table-column
                prop="userName"
                label="登录账号"
              />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { deleteCarRuleAPI, getCarRuleDetailAPI } from '@/api/role'
import { getCarRuleListAPI, getCarRulesAPI, getCarRuleTreeAPI } from '@/api/role'
import { addDisabled } from '@/utils/validate'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      activeIndex: 0,
      treeList: [],
      parm: [], // 当前权限点列表
      activeName: 'tree',
      userList: []
    }
  },
  created() {
  },
  async mounted() {
    await this.getRoleList()
    await this.getTreeList()
    if (this.roleList.length > 0) {
      // 添加一个小延时确保树组件已经渲染完成
      setTimeout(() => {
        this.getRoleTree(this.roleList[0].roleId)
      }, 100)
    }
    this.getUserList(this.roleList[0].roleId)
  },
  methods: {
    async getRoleList() {
      const res = await getCarRulesAPI()
      console.log('角色', res)
      this.roleList = res.data
    },
    changeAtive(index) {
      this.activeIndex = index
      // 获取高亮角色的id
      const roleId = this.roleList[index].roleId
      console.log(roleId)
      this.getRoleTree(roleId)
      this.getUserList(roleId)
    },
    async getTreeList() {
      const res = await getCarRuleTreeAPI()
      console.log('树', res)
      this.treeList = res.data
      // 禁用
      // 目标：treeList里面的每一项以及嵌套的子项都添加一个disabled = true
      addDisabled(this.treeList)
    },
    async getRoleTree(roleId) {
      try {
        const res = await getCarRuleDetailAPI(roleId)
        console.log('角色权限', res)

        // 确保 perms 存在且是数组
        this.parm = res.data.perms || []

        // 确保 this.$refs.tree 存在且是数组
        const treeComponentList = this.$refs.tree || []

        treeComponentList.forEach((tree, index) => {
          // 确保 tree 是有效的组件实例且 this.parm[index] 存在
          if (tree && this.parm[index]) {
            tree.setCheckedKeys(this.parm[index])
          } else if (tree) {
            // 如果组件存在但没有对应的权限数据
            tree.setCheckedKeys([])
          }
        })
      } catch (error) {
        console.error('获取角色权限失败:', error)
        this.$message.error('获取角色权限失败')
      }
    },
    async getUserList(roleId) {
      const res = await getCarRuleListAPI(roleId)
      console.log('用户', res)
      this.userList = res.data.rows
    },
    delRole(roleId) {
      this.$confirm('确定要删除吗').then(async() => {
        await deleteCarRuleAPI(roleId)
        this.getRoleList()
        this.$message.success('删除成功')
      })
    }
  }
}
</script>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;
  padding:20px;
  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
      }
    }

    .more {
      display: flex;
      align-items: center;
    }
    .addBtn{
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper{
      padding:20px;
    }
  }
}
</style>
